package com.example.kotlinlearningproject.network

import android.content.Context
import android.media.MediaPlayer
import android.util.Log
import com.example.kotlinlearningproject.utils.Const
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okio.buffer
import okio.sink
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

private const val TAG = "DownloadHandler"

class DownloadHandler(context: Context) {

    private var mContext: Context = context
    private var okHttpClient: OkHttpClient = OkHttpClient()
    private val fileName = "xxx.mp3"
    private val fileName2 = "222.wav"

    fun downloadAudio(path: String) {
        val request = Request.Builder()
            .url(path)
            .build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e(TAG, "Download audio failed")
            }

            override fun onResponse(call: Call, response: Response) {
                writeToSDCard(response)
                playAudio(fileName)
            }
        })
    }

    fun downloadAudioSync(path: String) {
        Log.e(TAG, "download url: $path file name: $fileName2")
        val request = Request.Builder().url(path).build()
        try {
            val response = okHttpClient.newCall(request).execute()
            // 检查响应是否成功
            if (!response.isSuccessful) throw Exception("Failed to download file: HTTP error code : "
                    + response.code)

            val savePath = mContext.getExternalFilesDir(null).toString() + File.separator +
                    Const.APP_FOLDER
            val dir = File(savePath)
            val file = File(dir, fileName2)
            // 使用Okio库简化文件写入操作
            val source = response.body?.source() ?: throw Exception("No source found!")
            val sink = FileOutputStream(file).sink().buffer()
            sink.writeAll(source)
            sink.close()
            println("File downloaded successfully: ${file.absolutePath}")
            playAudio(fileName2)
        } catch (exception: Exception) {
            Log.e(TAG, "Download audio failed: $exception")
        }
    }

    private fun writeToSDCard(response: Response) {
        // val savePath = Environment.getExternalStorageDirectory().absolutePath + File.separator + APP_FOLDER
        val savePath = mContext.getExternalFilesDir(null).toString() + File.separator + Const.APP_FOLDER
        val dir = File(savePath)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val file = File(dir, fileName)
        val fileOutputStream: FileOutputStream?
        val fileReader = ByteArray(4096)
        val fileSize = response.body!!.contentLength()
        var sum: Long = 0
        val inputStream: InputStream? = response.body?.byteStream()
        fileOutputStream = FileOutputStream(file)
        var read: Int
        while (inputStream?.read(fileReader).also { read = it!! } != -1) {
            fileOutputStream.write(fileReader, 0, read)
            sum += read.toLong()
            val progress = (sum * 1.0 / fileSize * 100).toInt()
            Log.e(TAG,"downloaded $sum of $fileSize, progress: $progress")
        }
        fileOutputStream.flush()
        Log.e(TAG, "Download audio completed")
        inputStream?.close()
        fileOutputStream.close()
    }

    private fun playAudio(audioName: String) {
        val mediaPlayer = MediaPlayer()
        mediaPlayer.setDataSource(mContext.getExternalFilesDir(null).toString()
                + File.separator + Const.APP_FOLDER + audioName)
        // 同步准备并播放
        mediaPlayer.prepare()
        Log.d(TAG, "prepare完成**********")
        mediaPlayer.start()
    }
}